<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>OpenCV: Sobel Derivatives</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<script type="text/javascript" src="../../tutorial-utils.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
//<![CDATA[
MathJax.Hub.Config(
{
  TeX: {
      Macros: {
          matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9],
          fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4],
          forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6],
          forkfour: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ #7 & \\mbox{#8}\\\\ \\end{array} \\right.", 8],
          vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3],
          vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9],
          cameramatrix: ["#1 = \\begin{bmatrix} f_x & 0 & c_x\\\\ 0 & f_y & c_y\\\\ 0 & 0 & 1 \\end{bmatrix}", 1],
          distcoeffs: ["(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \\tau_x, \\tau_y]]]]) \\text{ of 4, 5, 8, 12 or 14 elements}"],
          distcoeffsfisheye: ["(k_1, k_2, k_3, k_4)"],
          hdotsfor: ["\\dots", 1],
          mathbbm: ["\\mathbb{#1}", 1],
          bordermatrix: ["\\matrix{#1}", 1]
      }
  }
}
);
//]]>
</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<!--#include virtual="/google-search.html"-->
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"/></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">OpenCV
   &#160;<span id="projectnumber">4.5.2</span>
   </div>
   <div id="projectbrief">Open Source Computer Vision</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
  initMenu('../../',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div id="nav-path" class="navpath">
  <ul>
<li class="navelem"><a class="el" href="../../d9/df8/tutorial_root.html">OpenCV Tutorials</a></li><li class="navelem"><a class="el" href="../../d7/da8/tutorial_table_of_content_imgproc.html">Image Processing (imgproc module)</a></li>  </ul>
</div>
</div><!-- top -->
<div class="header">
  <div class="headertitle">
<div class="title">Sobel Derivatives </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p><b>Prev Tutorial:</b> <a class="el" href="../../dc/da3/tutorial_copyMakeBorder.html">Adding borders to your images</a></p>
<p><b>Next Tutorial:</b> <a class="el" href="../../d5/db5/tutorial_laplace_operator.html">Laplace Operator</a></p>
<table class="doxtable">
<tr>
<th align="right"></th><th align="left"></th></tr>
<tr>
<td align="right">Original author </td><td align="left">Ana Huamán </td></tr>
<tr>
<td align="right">Compatibility </td><td align="left">OpenCV &gt;= 3.0 </td></tr>
</table>
<h2>Goal </h2>
<p>In this tutorial you will learn how to:</p>
<ul>
<li>Use the OpenCV function <b><a class="el" href="../../d4/d86/group__imgproc__filter.html#gacea54f142e81b6758cb6f375ce782c8d" title="Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator...">Sobel()</a></b> to calculate the derivatives from an image.</li>
<li>Use the OpenCV function <b><a class="el" href="../../d4/d86/group__imgproc__filter.html#gaa13106761eedf14798f37aa2d60404c9" title="Calculates the first x- or y- image derivative using Scharr operator. ">Scharr()</a></b> to calculate a more accurate derivative for a kernel of size \(3 \cdot 3\)</li>
</ul>
<h2>Theory </h2>
<dl class="section note"><dt>Note</dt><dd>The explanation below belongs to the book <b>Learning OpenCV</b> by Bradski and Kaehler.</dd></dl>
<ol type="1">
<li>In the last two tutorials we have seen applicative examples of convolutions. One of the most important convolutions is the computation of derivatives in an image (or an approximation to them).</li>
<li><p class="startli">Why may be important the calculus of the derivatives in an image? Let's imagine we want to detect the <em>edges</em> present in the image. For instance:</p>
<div class="image">
<img src="../../Sobel_Derivatives_Tutorial_Theory_0.jpg" alt="Sobel_Derivatives_Tutorial_Theory_0.jpg"/>
</div>
<p class="startli">You can easily notice that in an <em>edge</em>, the pixel intensity <em>changes</em> in a notorious way. A good way to express <em>changes</em> is by using <em>derivatives</em>. A high change in gradient indicates a major change in the image.</p>
</li>
<li><p class="startli">To be more graphical, let's assume we have a 1D-image. An edge is shown by the "jump" in intensity in the plot below:</p>
<div class="image">
<img src="../../Sobel_Derivatives_Tutorial_Theory_Intensity_Function.jpg" alt="Sobel_Derivatives_Tutorial_Theory_Intensity_Function.jpg"/>
</div>
</li>
<li><p class="startli">The edge "jump" can be seen more easily if we take the first derivative (actually, here appears as a maximum)</p>
<div class="image">
<img src="../../Sobel_Derivatives_Tutorial_Theory_dIntensity_Function.jpg" alt="Sobel_Derivatives_Tutorial_Theory_dIntensity_Function.jpg"/>
</div>
</li>
<li>So, from the explanation above, we can deduce that a method to detect edges in an image can be performed by locating pixel locations where the gradient is higher than its neighbors (or to generalize, higher than a threshold).</li>
<li>More detailed explanation, please refer to <b>Learning OpenCV</b> by Bradski and Kaehler</li>
</ol>
<h3>Sobel Operator</h3>
<ol type="1">
<li>The Sobel Operator is a discrete differentiation operator. It computes an approximation of the gradient of an image intensity function.</li>
<li>The Sobel Operator combines Gaussian smoothing and differentiation.</li>
</ol>
<h4>Formulation</h4>
<p>Assuming that the image to be operated is \(I\):</p>
<ol type="1">
<li><p class="startli">We calculate two derivatives:</p><ol type="a">
<li><b>Horizontal changes</b>: This is computed by convolving \(I\) with a kernel \(G_{x}\) with odd size. For example for a kernel size of 3, \(G_{x}\) would be computed as:</li>
</ol>
<p class="formulaDsp">
\[G_{x} = \begin{bmatrix} -1 &amp; 0 &amp; +1 \\ -2 &amp; 0 &amp; +2 \\ -1 &amp; 0 &amp; +1 \end{bmatrix} * I\]
</p>
<ol type="a">
<li><b>Vertical changes</b>: This is computed by convolving \(I\) with a kernel \(G_{y}\) with odd size. For example for a kernel size of 3, \(G_{y}\) would be computed as:</li>
</ol>
<p class="formulaDsp">
\[G_{y} = \begin{bmatrix} -1 &amp; -2 &amp; -1 \\ 0 &amp; 0 &amp; 0 \\ +1 &amp; +2 &amp; +1 \end{bmatrix} * I\]
</p>
</li>
<li><p class="startli">At each point of the image we calculate an approximation of the <em>gradient</em> in that point by combining both results above:</p>
<p class="formulaDsp">
\[G = \sqrt{ G_{x}^{2} + G_{y}^{2} }\]
</p>
<p class="startli">Although sometimes the following simpler equation is used:</p>
<p class="formulaDsp">
\[G = |G_{x}| + |G_{y}|\]
</p>
</li>
</ol>
<dl class="section note"><dt>Note</dt><dd>When the size of the kernel is <code>3</code>, the Sobel kernel shown above may produce noticeable inaccuracies (after all, Sobel is only an approximation of the derivative). OpenCV addresses this inaccuracy for kernels of size 3 by using the <b><a class="el" href="../../d4/d86/group__imgproc__filter.html#gaa13106761eedf14798f37aa2d60404c9" title="Calculates the first x- or y- image derivative using Scharr operator. ">Scharr()</a></b> function. This is as fast but more accurate than the standard Sobel function. It implements the following kernels: <p class="formulaDsp">
\[G_{x} = \begin{bmatrix} -3 &amp; 0 &amp; +3 \\ -10 &amp; 0 &amp; +10 \\ -3 &amp; 0 &amp; +3 \end{bmatrix}\]
</p>
 <p class="formulaDsp">
\[G_{y} = \begin{bmatrix} -3 &amp; -10 &amp; -3 \\ 0 &amp; 0 &amp; 0 \\ +3 &amp; +10 &amp; +3 \end{bmatrix}\]
</p>
 </dd>
<dd>
You can check out more information of this function in the OpenCV reference - <b><a class="el" href="../../d4/d86/group__imgproc__filter.html#gaa13106761eedf14798f37aa2d60404c9" title="Calculates the first x- or y- image derivative using Scharr operator. ">Scharr()</a></b> . Also, in the sample code below, you will notice that above the code for <b><a class="el" href="../../d4/d86/group__imgproc__filter.html#gacea54f142e81b6758cb6f375ce782c8d" title="Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator...">Sobel()</a></b> function there is also code for the <b><a class="el" href="../../d4/d86/group__imgproc__filter.html#gaa13106761eedf14798f37aa2d60404c9" title="Calculates the first x- or y- image derivative using Scharr operator. ">Scharr()</a></b> function commented. Uncommenting it (and obviously commenting the Sobel stuff) should give you an idea of how this function works.</dd></dl>
<h2>Code </h2>
<ol type="1">
<li><b>What does this program do?</b><ul>
<li>Applies the <em>Sobel Operator</em> and generates as output an image with the detected <em>edges</em> bright on a darker background.</li>
</ul>
</li>
<li>The tutorial code's is shown lines below.</li>
</ol>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'><p> You can also download it from <a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/cpp/tutorial_code/ImgTrans/Sobel_Demo.cpp">here</a> </p><div class="fragment"><div class="line"></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d1/d4f/imgproc_2include_2opencv2_2imgproc_8hpp.html">opencv2/imgproc.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d6/d87/imgcodecs_8hpp.html">opencv2/imgcodecs.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d4/dd5/highgui_8hpp.html">opencv2/highgui.hpp</a>&quot;</span></div><div class="line"></div><div class="line"><span class="preprocessor">#include &lt;iostream&gt;</span></div><div class="line"></div><div class="line"><span class="keyword">using namespace </span><a class="code" href="../../d2/d75/namespacecv.html">cv</a>;</div><div class="line"><span class="keyword">using namespace </span>std;</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>** argv )</div><div class="line">{</div><div class="line">  <a class="code" href="../../d0/d2e/classcv_1_1CommandLineParser.html">cv::CommandLineParser</a> parser(argc, argv,</div><div class="line">                               <span class="stringliteral">&quot;{@input   |lena.jpg|input image}&quot;</span></div><div class="line">                               <span class="stringliteral">&quot;{ksize   k|1|ksize (hit &#39;K&#39; to increase its value at run time)}&quot;</span></div><div class="line">                               <span class="stringliteral">&quot;{scale   s|1|scale (hit &#39;S&#39; to increase its value at run time)}&quot;</span></div><div class="line">                               <span class="stringliteral">&quot;{delta   d|0|delta (hit &#39;D&#39; to increase its value at run time)}&quot;</span></div><div class="line">                               <span class="stringliteral">&quot;{help    h|false|show help message}&quot;</span>);</div><div class="line"></div><div class="line">  cout &lt;&lt; <span class="stringliteral">&quot;The sample uses Sobel or Scharr OpenCV functions for edge detection\n\n&quot;</span>;</div><div class="line">  parser.printMessage();</div><div class="line">  cout &lt;&lt; <span class="stringliteral">&quot;\nPress &#39;ESC&#39; to exit program.\nPress &#39;R&#39; to reset values ( ksize will be -1 equal to Scharr function )&quot;</span>;</div><div class="line"></div><div class="line">  <span class="comment">// First we declare the variables we are going to use</span></div><div class="line">  <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> image,src, src_gray;</div><div class="line">  <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> grad;</div><div class="line">  <span class="keyword">const</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> window_name = <span class="stringliteral">&quot;Sobel Demo - Simple Edge Detector&quot;</span>;</div><div class="line">  <span class="keywordtype">int</span> ksize = parser.get&lt;<span class="keywordtype">int</span>&gt;(<span class="stringliteral">&quot;ksize&quot;</span>);</div><div class="line">  <span class="keywordtype">int</span> scale = parser.get&lt;<span class="keywordtype">int</span>&gt;(<span class="stringliteral">&quot;scale&quot;</span>);</div><div class="line">  <span class="keywordtype">int</span> delta = parser.get&lt;<span class="keywordtype">int</span>&gt;(<span class="stringliteral">&quot;delta&quot;</span>);</div><div class="line">  <span class="keywordtype">int</span> ddepth = <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga9d2ee1a8334733dea7482a47a88e0f87">CV_16S</a>;</div><div class="line"></div><div class="line">  <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> imageName = parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;(<span class="stringliteral">&quot;@input&quot;</span>);</div><div class="line">  <span class="comment">// As usual we load our source image (src)</span></div><div class="line">  image = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">samples::findFile</a>( imageName ), <a class="code" href="../../d8/d6a/group__imgcodecs__flags.html#gga61d9b0126a3e57d9277ac48327799c80af660544735200cbe942eea09232eb822">IMREAD_COLOR</a> ); <span class="comment">// Load an image</span></div><div class="line"></div><div class="line">  <span class="comment">// Check if image is loaded fine</span></div><div class="line">  <span class="keywordflow">if</span>( image.empty() )</div><div class="line">  {</div><div class="line">    printf(<span class="stringliteral">&quot;Error opening image: %s\n&quot;</span>, imageName.c_str());</div><div class="line">    <span class="keywordflow">return</span> EXIT_FAILURE;</div><div class="line">  }</div><div class="line"></div><div class="line">  <span class="keywordflow">for</span> (;;)</div><div class="line">  {</div><div class="line">    <span class="comment">// Remove noise by blurring with a Gaussian filter ( kernel size = 3 )</span></div><div class="line">    <a class="code" href="../../d4/d86/group__imgproc__filter.html#gaabe8c836e97159a9193fb0b11ac52cf1">GaussianBlur</a>(image, src, <a class="code" href="../../dc/d84/group__core__basic.html#ga346f563897249351a34549137c8532a0">Size</a>(3, 3), 0, 0, <a class="code" href="../../d2/de8/group__core__array.html#gga209f2f4869e304c82d07739337eae7c5afe14c13a4ea8b8e3b3ef399013dbae01">BORDER_DEFAULT</a>);</div><div class="line"></div><div class="line">    <span class="comment">// Convert the image to grayscale</span></div><div class="line">    <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cvtColor</a>(src, src_gray, <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#gga4e0972be5de079fed4e3a10e24ef5ef0a353a4b8db9040165db4dacb5bcefb6ea">COLOR_BGR2GRAY</a>);</div><div class="line"></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> grad_x, grad_y;</div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> abs_grad_x, abs_grad_y;</div><div class="line"></div><div class="line">    <a class="code" href="../../d4/d86/group__imgproc__filter.html#gacea54f142e81b6758cb6f375ce782c8d">Sobel</a>(src_gray, grad_x, ddepth, 1, 0, ksize, scale, delta, <a class="code" href="../../d2/de8/group__core__array.html#gga209f2f4869e304c82d07739337eae7c5afe14c13a4ea8b8e3b3ef399013dbae01">BORDER_DEFAULT</a>);</div><div class="line"></div><div class="line">    <a class="code" href="../../d4/d86/group__imgproc__filter.html#gacea54f142e81b6758cb6f375ce782c8d">Sobel</a>(src_gray, grad_y, ddepth, 0, 1, ksize, scale, delta, <a class="code" href="../../d2/de8/group__core__array.html#gga209f2f4869e304c82d07739337eae7c5afe14c13a4ea8b8e3b3ef399013dbae01">BORDER_DEFAULT</a>);</div><div class="line"></div><div class="line">    <span class="comment">// converting back to CV_8U</span></div><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#ga3460e9c9f37b563ab9dd550c4d8c4e7d">convertScaleAbs</a>(grad_x, abs_grad_x);</div><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#ga3460e9c9f37b563ab9dd550c4d8c4e7d">convertScaleAbs</a>(grad_y, abs_grad_y);</div><div class="line"></div><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#gafafb2513349db3bcff51f54ee5592a19">addWeighted</a>(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(window_name, grad);</div><div class="line">    <span class="keywordtype">char</span> key = (char)<a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>(0);</div><div class="line"></div><div class="line">    <span class="keywordflow">if</span>(key == 27)</div><div class="line">    {</div><div class="line">      <span class="keywordflow">return</span> EXIT_SUCCESS;</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keywordflow">if</span> (key == <span class="charliteral">&#39;k&#39;</span> || key == <span class="charliteral">&#39;K&#39;</span>)</div><div class="line">    {</div><div class="line">      ksize = ksize &lt; 30 ? ksize+2 : -1;</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keywordflow">if</span> (key == <span class="charliteral">&#39;s&#39;</span> || key == <span class="charliteral">&#39;S&#39;</span>)</div><div class="line">    {</div><div class="line">      scale++;</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keywordflow">if</span> (key == <span class="charliteral">&#39;d&#39;</span> || key == <span class="charliteral">&#39;D&#39;</span>)</div><div class="line">    {</div><div class="line">      delta++;</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keywordflow">if</span> (key == <span class="charliteral">&#39;r&#39;</span> || key == <span class="charliteral">&#39;R&#39;</span>)</div><div class="line">    {</div><div class="line">      scale =  1;</div><div class="line">      ksize = -1;</div><div class="line">      delta =  0;</div><div class="line">    }</div><div class="line">  }</div><div class="line">  <span class="keywordflow">return</span> EXIT_SUCCESS;</div><div class="line">}</div></div><!-- fragment -->  </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'><p> You can also download it from <a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/java/tutorial_code/ImgTrans/SobelDemo/SobelDemo.java">here</a> </p><div class="fragment"><div class="line"></div><div class="line"><span class="keyword">import</span> org.opencv.core.*;</div><div class="line"><span class="keyword">import</span> org.opencv.highgui.HighGui;</div><div class="line"><span class="keyword">import</span> org.opencv.imgcodecs.Imgcodecs;</div><div class="line"><span class="keyword">import</span> org.opencv.imgproc.Imgproc;</div><div class="line"></div><div class="line"><span class="keyword">class </span>SobelDemoRun {</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="keywordtype">void</span> run(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line"></div><div class="line">        <span class="comment">// First we declare the variables we are going to use</span></div><div class="line">        Mat src, src_gray = <span class="keyword">new</span> Mat();</div><div class="line">        Mat grad = <span class="keyword">new</span> Mat();</div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> window_name = <span class="stringliteral">&quot;Sobel Demo - Simple Edge Detector&quot;</span>;</div><div class="line">        <span class="keywordtype">int</span> scale = 1;</div><div class="line">        <span class="keywordtype">int</span> delta = 0;</div><div class="line">        <span class="keywordtype">int</span> ddepth = CvType.CV_16S;</div><div class="line"></div><div class="line">        <span class="comment">// As usual we load our source image (src)</span></div><div class="line">        <span class="comment">// Check number of arguments</span></div><div class="line">        <span class="keywordflow">if</span> (args.length == 0){</div><div class="line">            System.out.println(<span class="stringliteral">&quot;Not enough parameters!&quot;</span>);</div><div class="line">            System.out.println(<span class="stringliteral">&quot;Program Arguments: [image_path]&quot;</span>);</div><div class="line">            System.exit(-1);</div><div class="line">        }</div><div class="line"></div><div class="line">        <span class="comment">// Load the image</span></div><div class="line">        src = Imgcodecs.imread(args[0]);</div><div class="line"></div><div class="line">        <span class="comment">// Check if image is loaded fine</span></div><div class="line">        <span class="keywordflow">if</span>( src.empty() ) {</div><div class="line">            System.out.println(<span class="stringliteral">&quot;Error opening image: &quot;</span> + args[0]);</div><div class="line">            System.exit(-1);</div><div class="line">        }</div><div class="line"></div><div class="line">        <span class="comment">// Remove noise by blurring with a Gaussian filter ( kernel size = 3 )</span></div><div class="line">        Imgproc.GaussianBlur( src, src, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga346f563897249351a34549137c8532a0">Size</a>(3, 3), 0, 0, Core.BORDER_DEFAULT );</div><div class="line"></div><div class="line">        <span class="comment">// Convert the image to grayscale</span></div><div class="line">        Imgproc.cvtColor( src, src_gray, Imgproc.COLOR_RGB2GRAY );</div><div class="line"></div><div class="line">        Mat grad_x = <span class="keyword">new</span> Mat(), grad_y = <span class="keyword">new</span> Mat();</div><div class="line">        Mat abs_grad_x = <span class="keyword">new</span> Mat(), abs_grad_y = <span class="keyword">new</span> Mat();</div><div class="line"></div><div class="line">        <span class="comment">//Imgproc.Scharr( src_gray, grad_x, ddepth, 1, 0, scale, delta, Core.BORDER_DEFAULT );</span></div><div class="line">        Imgproc.Sobel( src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, Core.BORDER_DEFAULT );</div><div class="line"></div><div class="line">        <span class="comment">//Imgproc.Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, Core.BORDER_DEFAULT );</span></div><div class="line">        Imgproc.Sobel( src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, Core.BORDER_DEFAULT );</div><div class="line"></div><div class="line">        <span class="comment">// converting back to CV_8U</span></div><div class="line">        Core.convertScaleAbs( grad_x, abs_grad_x );</div><div class="line">        Core.convertScaleAbs( grad_y, abs_grad_y );</div><div class="line"></div><div class="line">        Core.addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad );</div><div class="line"></div><div class="line">        HighGui.imshow( window_name, grad );</div><div class="line">        HighGui.waitKey(0);</div><div class="line"></div><div class="line">        System.exit(0);</div><div class="line">    }</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">class </span>SobelDemo {</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keywordtype">void</span> main(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">        <span class="comment">// Load the native library.</span></div><div class="line">        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);</div><div class="line">        <span class="keyword">new</span> SobelDemoRun().run(args);</div><div class="line">    }</div><div class="line">}</div></div><!-- fragment -->  </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'><p> You can also download it from <a href="https://raw.githubusercontent.com/opencv/opencv/master/samples/python/tutorial_code/ImgTrans/SobelDemo/sobel_demo.py">here</a> </p><div class="fragment"><div class="line"><span class="stringliteral">&quot;&quot;&quot;</span></div><div class="line"><span class="stringliteral">@file sobel_demo.py</span></div><div class="line"><span class="stringliteral">@brief Sample code using Sobel and/or Scharr OpenCV functions to make a simple Edge Detector</span></div><div class="line"><span class="stringliteral">&quot;&quot;&quot;</span></div><div class="line"><span class="keyword">import</span> sys</div><div class="line"><span class="keyword">import</span> cv2 <span class="keyword">as</span> cv</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">def </span>main(argv):</div><div class="line">    </div><div class="line">    window_name = (<span class="stringliteral">&#39;Sobel Demo - Simple Edge Detector&#39;</span>)</div><div class="line">    scale = 1</div><div class="line">    delta = 0</div><div class="line">    ddepth = cv.CV_16S</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    <span class="keywordflow">if</span> len(argv) &lt; 1:</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Not enough parameters&#39;</span>)</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Usage:\nmorph_lines_detection.py &lt; path_to_image &gt;&#39;</span>)</div><div class="line">        <span class="keywordflow">return</span> -1</div><div class="line"></div><div class="line">    <span class="comment"># Load the image</span></div><div class="line">    src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">cv.imread</a>(argv[0], cv.IMREAD_COLOR)</div><div class="line"></div><div class="line">    <span class="comment"># Check if image is loaded fine</span></div><div class="line">    <span class="keywordflow">if</span> src <span class="keywordflow">is</span> <span class="keywordtype">None</span>:</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Error opening image: &#39;</span> + argv[0])</div><div class="line">        <span class="keywordflow">return</span> -1</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    src = <a class="code" href="../../d4/d86/group__imgproc__filter.html#gaabe8c836e97159a9193fb0b11ac52cf1">cv.GaussianBlur</a>(src, (3, 3), 0)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    gray = <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cv.cvtColor</a>(src, cv.COLOR_BGR2GRAY)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    grad_x = <a class="code" href="../../d4/d86/group__imgproc__filter.html#gacea54f142e81b6758cb6f375ce782c8d">cv.Sobel</a>(gray, ddepth, 1, 0, ksize=3, scale=scale, delta=delta, borderType=cv.BORDER_DEFAULT)</div><div class="line"></div><div class="line">    <span class="comment"># Gradient-Y</span></div><div class="line">    <span class="comment"># grad_y = cv.Scharr(gray,ddepth,0,1)</span></div><div class="line">    grad_y = <a class="code" href="../../d4/d86/group__imgproc__filter.html#gacea54f142e81b6758cb6f375ce782c8d">cv.Sobel</a>(gray, ddepth, 0, 1, ksize=3, scale=scale, delta=delta, borderType=cv.BORDER_DEFAULT)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    abs_grad_x = <a class="code" href="../../d2/de8/group__core__array.html#ga3460e9c9f37b563ab9dd550c4d8c4e7d">cv.convertScaleAbs</a>(grad_x)</div><div class="line">    abs_grad_y = <a class="code" href="../../d2/de8/group__core__array.html#ga3460e9c9f37b563ab9dd550c4d8c4e7d">cv.convertScaleAbs</a>(grad_y)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    grad = <a class="code" href="../../d2/de8/group__core__array.html#gafafb2513349db3bcff51f54ee5592a19">cv.addWeighted</a>(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    <a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(window_name, grad)</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">cv.waitKey</a>(0)</div><div class="line">    </div><div class="line"></div><div class="line">    <span class="keywordflow">return</span> 0</div><div class="line"></div><div class="line"><span class="keywordflow">if</span> __name__ == <span class="stringliteral">&quot;__main__&quot;</span>:</div><div class="line">    main(sys.argv[1:])</div></div><!-- fragment -->  </div> <h2>Explanation </h2>
<h4>Declare variables</h4>
<div class="fragment"><div class="line">  <span class="comment">// First we declare the variables we are going to use</span></div><div class="line">  Mat image,src, src_gray;</div><div class="line">  Mat grad;</div><div class="line">  <span class="keyword">const</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> window_name = <span class="stringliteral">&quot;Sobel Demo - Simple Edge Detector&quot;</span>;</div><div class="line">  <span class="keywordtype">int</span> ksize = parser.get&lt;<span class="keywordtype">int</span>&gt;(<span class="stringliteral">&quot;ksize&quot;</span>);</div><div class="line">  <span class="keywordtype">int</span> scale = parser.get&lt;<span class="keywordtype">int</span>&gt;(<span class="stringliteral">&quot;scale&quot;</span>);</div><div class="line">  <span class="keywordtype">int</span> delta = parser.get&lt;<span class="keywordtype">int</span>&gt;(<span class="stringliteral">&quot;delta&quot;</span>);</div><div class="line">  <span class="keywordtype">int</span> ddepth = <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga9d2ee1a8334733dea7482a47a88e0f87">CV_16S</a>;</div></div><!-- fragment --> <h4>Load source image</h4>
<div class="fragment"><div class="line">  <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> imageName = parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;(<span class="stringliteral">&quot;@input&quot;</span>);</div><div class="line">  <span class="comment">// As usual we load our source image (src)</span></div><div class="line">  image = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">samples::findFile</a>( imageName ), <a class="code" href="../../d8/d6a/group__imgcodecs__flags.html#gga61d9b0126a3e57d9277ac48327799c80af660544735200cbe942eea09232eb822">IMREAD_COLOR</a> ); <span class="comment">// Load an image</span></div><div class="line"></div><div class="line">  <span class="comment">// Check if image is loaded fine</span></div><div class="line">  <span class="keywordflow">if</span>( image.empty() )</div><div class="line">  {</div><div class="line">    printf(<span class="stringliteral">&quot;Error opening image: %s\n&quot;</span>, imageName.c_str());</div><div class="line">    <span class="keywordflow">return</span> EXIT_FAILURE;</div><div class="line">  }</div></div><!-- fragment --> <h4>Reduce noise</h4>
<div class="fragment"><div class="line">    <span class="comment">// Remove noise by blurring with a Gaussian filter ( kernel size = 3 )</span></div><div class="line">    <a class="code" href="../../d4/d86/group__imgproc__filter.html#gaabe8c836e97159a9193fb0b11ac52cf1">GaussianBlur</a>(image, src, <a class="code" href="../../dc/d84/group__core__basic.html#ga346f563897249351a34549137c8532a0">Size</a>(3, 3), 0, 0, <a class="code" href="../../d2/de8/group__core__array.html#gga209f2f4869e304c82d07739337eae7c5afe14c13a4ea8b8e3b3ef399013dbae01">BORDER_DEFAULT</a>);</div></div><!-- fragment --> <h4>Grayscale</h4>
<div class="fragment"><div class="line">    <span class="comment">// Convert the image to grayscale</span></div><div class="line">    <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cvtColor</a>(src, src_gray, <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#gga4e0972be5de079fed4e3a10e24ef5ef0a353a4b8db9040165db4dacb5bcefb6ea">COLOR_BGR2GRAY</a>);</div></div><!-- fragment --> <h4>Sobel Operator</h4>
<div class="fragment"><div class="line">    Mat grad_x, grad_y;</div><div class="line">    Mat abs_grad_x, abs_grad_y;</div><div class="line"></div><div class="line">    <a class="code" href="../../d4/d86/group__imgproc__filter.html#gacea54f142e81b6758cb6f375ce782c8d">Sobel</a>(src_gray, grad_x, ddepth, 1, 0, ksize, scale, delta, <a class="code" href="../../d2/de8/group__core__array.html#gga209f2f4869e304c82d07739337eae7c5afe14c13a4ea8b8e3b3ef399013dbae01">BORDER_DEFAULT</a>);</div><div class="line"></div><div class="line">    <a class="code" href="../../d4/d86/group__imgproc__filter.html#gacea54f142e81b6758cb6f375ce782c8d">Sobel</a>(src_gray, grad_y, ddepth, 0, 1, ksize, scale, delta, <a class="code" href="../../d2/de8/group__core__array.html#gga209f2f4869e304c82d07739337eae7c5afe14c13a4ea8b8e3b3ef399013dbae01">BORDER_DEFAULT</a>);</div></div><!-- fragment --><ul>
<li><p class="startli">We calculate the "derivatives" in <em>x</em> and <em>y</em> directions. For this, we use the function <b><a class="el" href="../../d4/d86/group__imgproc__filter.html#gacea54f142e81b6758cb6f375ce782c8d" title="Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator...">Sobel()</a></b> as shown below: The function takes the following arguments:</p><ul>
<li><em>src_gray</em>: In our example, the input image. Here it is <em>CV_8U</em></li>
<li><em>grad_x</em> / <em>grad_y</em> : The output image.</li>
<li><em>ddepth</em>: The depth of the output image. We set it to <em>CV_16S</em> to avoid overflow.</li>
<li><em>x_order</em>: The order of the derivative in <b>x</b> direction.</li>
<li><em>y_order</em>: The order of the derivative in <b>y</b> direction.</li>
<li><em>scale</em>, <em>delta</em> and <em>BORDER_DEFAULT</em>: We use default values.</li>
</ul>
<p class="startli">Notice that to calculate the gradient in <em>x</em> direction we use: \(x_{order}= 1\) and \(y_{order} = 0\). We do analogously for the <em>y</em> direction.</p>
</li>
</ul>
<h4>Convert output to a CV_8U image</h4>
<div class="fragment"><div class="line">    <span class="comment">// converting back to CV_8U</span></div><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#ga3460e9c9f37b563ab9dd550c4d8c4e7d">convertScaleAbs</a>(grad_x, abs_grad_x);</div><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#ga3460e9c9f37b563ab9dd550c4d8c4e7d">convertScaleAbs</a>(grad_y, abs_grad_y);</div></div><!-- fragment --> <h4>Gradient</h4>
<div class="fragment"><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#gafafb2513349db3bcff51f54ee5592a19">addWeighted</a>(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);</div></div><!-- fragment --><p> We try to approximate the <em>gradient</em> by adding both directional gradients (note that this is not an exact calculation at all! but it is good for our purposes).</p>
<h4>Show results</h4>
<div class="fragment"><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(window_name, grad);</div><div class="line">    <span class="keywordtype">char</span> key = (char)<a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>(0);</div></div><!-- fragment --> <h2>Results </h2>
<ol type="1">
<li><p class="startli">Here is the output of applying our basic detector to <em>lena.jpg</em>:</p>
<div class="image">
<img src="../../Sobel_Derivatives_Tutorial_Result.jpg" alt="Sobel_Derivatives_Tutorial_Result.jpg"/>
</div>
 </li>
</ol>
</div></div><!-- contents -->
<!-- HTML footer for doxygen 1.8.6-->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Apr 2 2021 11:36:35 for OpenCV by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
<script type="text/javascript">
//<![CDATA[
addTutorialsButtons();
//]]>
</script>
</body>
</html>
